package Euler49;

import java.util.*;
import ReusableCode.MathFunctions;
import ReusableCode.PrimeFunctions;

public class PrimePermutations {
	public static void main(String[] args) {
		List<Integer> primes = PrimeFunctions.GetPrimes(10000);
		List<String> answers = new ArrayList<String>();
		
		Iterator<Integer> iter = primes.iterator();
		while(iter.hasNext())
		{
			int prime = iter.next();
			if((prime/1000)>0)
			{
				List<Long> perms = MathFunctions.getNumberPermutations(prime);
				Map<Long, Boolean> primePerms = new HashMap<Long, Boolean>();
				
				//Get all permutations that are primes.
				for(int i = 0; i < perms.size(); i++)
				{
					if(primes.contains(MathFunctions.safeLongToInt(perms.get(i))) && (perms.get(i)/1000>0))
					{
						primePerms.put(perms.get(i),true);
					}
				}
				
				if(primePerms.size()>=3)
				{
					//Sort the primes in ascending order.
					List<Long> keys = new ArrayList<Long>();
					keys.addAll(primePerms.keySet());
					Collections.sort(keys);
					
					List<Long> vals = getPattern(keys);
					
					if(vals.size()==3)
					{
						String temp = vals.get(0) + "" + vals.get(1) + "" + vals.get(2);
						if(!answers.contains(temp))
						{
							answers.add(temp);
						}
					}
				}
			}
		}
		
		System.out.println(answers);
	}
	
	static List<Long> getPattern(List<Long> keys)
	{
		List<Long> vals = new ArrayList<Long>();
		long max = ((10000+1000)/3);
		
		for(int i = 0; i < keys.size()-2; i++)
		{
			long key = keys.get(i);
			int count = i+1;	
			
			while(count < keys.size()-1)
			{
				long otherKey = keys.get(count);
				long diff = (otherKey - key);
				
				if(diff < max)
				{
					if(keys.contains(otherKey+diff))
					{
						vals.add(key);
						vals.add(otherKey);
						vals.add(otherKey+diff);
						return vals;
					}
				}
				
				count++;
			}
		}
		
		return vals;
	}
}









